package xyz.heyaoshare.utils.captcha;

import com.wf.captcha.*;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

import static xyz.heyaoshare.exceptions.code.ErrorInfo.CAPTCHA_ERROR;
import static xyz.heyaoshare.exceptions.customize.ServerException.exception;

/**
 * 校验码工具类【基于easy-captcha】
 * @author YueHe
 * @version 0.0.1
 * @since 2025/6/25 上午10:39
 */
@Slf4j
public class CaptchaUtils {

    /**
     * 生成验证码【默认：算术】
     *
     * @return 生成的验证码对象
     */
    public static CaptchaBO generateCaptcha() {
        return generateCaptcha(CaptchaTypeEnum.ARITHMETIC);
    }

    /**
     * 生成验证码
     *
     * @param type 验证码类型【默认：算术】
     * @return 验证码对象
     * @throws xyz.heyaoshare.exceptions.customize.ServerException 验证码生成过程中出现的异常
     */
    public static CaptchaBO generateCaptcha(CaptchaTypeEnum type) {
        if (type == null) type = CaptchaTypeEnum.ARITHMETIC;
        String text;
        String image;
        String key = UUID.randomUUID().toString();
        switch (type) {
            case ARITHMETIC -> {
                ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha();
                text = arithmeticCaptcha.text();
                image = arithmeticCaptcha.toBase64();
            }
            case CHINESE -> {
                ChineseCaptcha chineseCaptcha = new ChineseCaptcha();
                text = chineseCaptcha.text();
                image = chineseCaptcha.toBase64();
            }
            case CHINESE_GIF -> {
                ChineseGifCaptcha chineseGifCaptcha = new ChineseGifCaptcha();
                text = chineseGifCaptcha.text();
                image = chineseGifCaptcha.toBase64();
            }
            case GIF -> {
                GifCaptcha gifCaptcha = new GifCaptcha();
                text = gifCaptcha.text();
                image = gifCaptcha.toBase64();
            }
            case SPEC -> {
                SpecCaptcha specCaptcha = new SpecCaptcha();
                text = specCaptcha.text();
                image = specCaptcha.toBase64();
            }
            default -> {
                log.error("验证码类型错误");
                throw exception(CAPTCHA_ERROR);
            }
        }
        // 生成验证码图片
        return new CaptchaBO(key, image, text);
    }

}